package com.xinggq.common.config;

import com.xinggq.common.context.UserContext;
import com.xinggq.common.context.UserContextProvider;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * 用户上下文自动配置类
 * 自动设置UserContext的环境信息并注册所有可用的UserContextProvider
 * 
 * @author xinggq
 * @since 2025/1/20
 */
@Configuration
@ConditionalOnClass(UserContext.class)
public class UserContextConfig {

  @Autowired
  private Environment environment;

  @Autowired
  private ApplicationContext applicationContext;

  /**
   * 初始化UserContext的环境信息和Provider
   */
  @PostConstruct
  public void initUserContext() {
    // 设置环境信息（这会自动注册TestUserContextProvider）
    UserContext.setEnvironment(environment);
    
    // 查找并注册所有UserContextProvider实现
    Map<String, UserContextProvider> providers = applicationContext.getBeansOfType(UserContextProvider.class);
    for (UserContextProvider provider : providers.values()) {
      UserContext.registerProvider(provider);
    }
  }
}